package com.dfch.auto.appium.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author ldcmaxim on 05/04/2018.
 *         线程池
 */
public class AutoThreadPool {
    private static AutoThreadPool mInstance;
    // 顺序线程池
    private ExecutorService mSingleThreadPool;
    // 异步线程池
    private ExecutorService mAsyncThreadPool;
    // 定时线程池
    private ScheduledExecutorService mScheduledThreadPool;

    public static synchronized AutoThreadPool getInstance() {
        if (mInstance == null) {
            mInstance = new AutoThreadPool();
        }
        return mInstance;
    }


    private AutoThreadPool() {
        mSingleThreadPool = Executors.newSingleThreadExecutor();
        mAsyncThreadPool = Executors.newCachedThreadPool();
        mScheduledThreadPool = Executors.newScheduledThreadPool(5);
    }

    /**
     * 执行异步任务
     */
    public void executeAsyncTask(Runnable task) {
        // 判断是否被关闭
        if (mAsyncThreadPool == null || mAsyncThreadPool.isShutdown()) {
            mAsyncThreadPool = Executors.newCachedThreadPool();
        }
        mAsyncThreadPool.execute(task);
    }

    /**
     * 顺序执行任务
     */
    public void executeOrderTask(Runnable task) {
        // 判断是否被关闭
        if (mSingleThreadPool == null || mSingleThreadPool.isShutdown()) {
            mSingleThreadPool = Executors.newSingleThreadExecutor();
        }
        mSingleThreadPool.execute(task);
    }

    /**
     * 顺序定时任务(最多5个)
     */
    public void executeScheduleTask(Runnable task, long delay) {
        // 判断是否被关闭
        if (mScheduledThreadPool == null || mScheduledThreadPool.isShutdown()) {
            mScheduledThreadPool = Executors.newScheduledThreadPool(5);
        }
        mScheduledThreadPool.schedule(task, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 关闭线程池
     */
    public void release() {
        if (mAsyncThreadPool != null && !mAsyncThreadPool.isShutdown()) {
            mAsyncThreadPool.shutdownNow();
            mAsyncThreadPool = null;
        }
        if (mSingleThreadPool != null && !mSingleThreadPool.isShutdown()) {
            mSingleThreadPool.shutdownNow();
            mSingleThreadPool = null;
        }
        if (mScheduledThreadPool != null && !mScheduledThreadPool.isShutdown()) {
            mScheduledThreadPool.shutdownNow();
            mScheduledThreadPool = null;
        }
    }
}
